# -*- coding: utf-8 -*-
'''
Created on 2013-4-11

@author: cl.lam
'''
from datetime import datetime as dt
import traceback
from flask import current_app as app
from flask import g, render_template, flash, session, redirect, url_for, request
from flask.blueprints import Blueprint
from sqlalchemy.sql.expression import and_, not_


from sys2do.views import BasicView
from sys2do.util.decorator import templated, loginRequired, activetab, \
    mypaginate, allPermission
from sys2do.model import db, qry, SysLog, Supplier, SysFile

from sys2do.util.common import _g, _gld, multiupload
from sys2do.util.logic_helper import getCurrentShopID, getCurrentUserID, \
    checkLogin, makeUpdateLog
from sys2do.constant import MSG_SAVE_SUCC, TAB_BASIC, MSG_SERVER_ERROR, \
    MESSAGE_ERROR, MESSAGE_INFO, MSG_UPDATE_SUCC, MSG_NO_ID_SUPPLIED, \
    MSG_RECORD_NOT_EXIST, LOG_TYPE_UPDATE, LOG_TYPE_CREATE, \
    MSG_SAME_NAME_RECORD_EXIST





__all__ = ['bpSpl']

bpSpl = Blueprint( 'bpSpl', __name__ )
@bpSpl.before_request
def _b():
    return checkLogin()

class SupplierView( BasicView ):

    template_folder = "mas.spl"

    dbclz = Supplier

    @templated( "index.html" )
    @activetab( TAB_BASIC )
    @mypaginate( 'result' )
    def index( self ):
        if request.method == 'POST':
            form = SrhForm( request.form )
            session[url_for( '.view' )] = form
        else:
            form = session.get( url_for( '.view' ), SrhForm( request.form ) )
        form.url = url_for( '.view' )

        cds = [self.dbclz.active == 0, ]
        if form.no.data : cds.append( self.dbclz.no.like( '%%%s%%' % form.no.data ) )
        if form.name.data : cds.append( self.dbclz.name.like( '%%%s%%' % form.name.data ) )
        if form.att.data : cds.append( self.dbclz.att.like( '%%%s%%' % form.att.data ) )
        if form.tel.data : cds.append( self.dbclz.tel.like( '%%%s%%' % form.tel.data ) )
        if form.mobile.data : cds.append( self.dbclz.mobile.like( '%%%s%%' % form.mobile.data ) )
        if form.createTimeFrom.data : cds.append( self.dbclz.createTime > form.createTimeFrom.data )
        if form.createTimeTo.data : cds.append( self.dbclz.createTime < form.createTimeTo.data )
        result = self.dbclz.iall( conditions = cds, order_by = self.dbclz.name )
        return {'result' : result, 'form' : form}


    @templated( 'view.html' )
    def view( self ):
        sid = _g( 'id' )
        if not sid :
            flash( MSG_NO_ID_SUPPLIED, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )
        obj = self.dbclz.get( sid )
        if not obj :
            flash( MSG_RECORD_NOT_EXIST, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )

        return {'obj' : obj}



    @templated( "add.html" )
    @allPermission( ['SUPPLIER_CREATE'] )
    @loginRequired
    def add( self ):
        if request.method != 'POST': return {}

        params = _gld( 'name', 'fullName', 'provinceID', 'cityID', 'address', 'tel', 'att', 'mobile' )
        if self._isDuplicate( params['name'] ) : return redirect( url_for( '.view', action = 'add' ) )

        try:
            params['attachment'] = multiupload()
            obj = self.dbclz.create( params )
            db.add( obj )
            db.flush()
            db.add( SysLog( refClz = obj.__class__.__name__, type = LOG_TYPE_CREATE, refID = obj.id ) )
            flash( MSG_SAVE_SUCC, MESSAGE_INFO )
            db.commit()
        except:
            db.rollback()
            traceback.print_exc()
            flash( MSG_SERVER_ERROR, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )
        else:
            return redirect( url_for( '.view', action = 'view', id = obj.id ) )


    @templated( "update.html" )
    @allPermission( ['SUPPLIER_EDIT'] )
    @loginRequired
    def update( self ):
        sid = _g( 'id' )
        if not sid :
            flash( MSG_NO_ID_SUPPLIED, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )
        obj = self.dbclz.get( sid )
        if not obj :
            flash( MSG_RECORD_NOT_EXIST, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )

        if request.method != 'POST': return {'obj' : obj}
        try:
            oldCopy = obj.serialize()
            extLog = []
            params = _gld( 'name', 'fullName', 'provinceID', 'cityID', 'address', 'att', 'tel', 'mobile', 'remark' )
            params.update( {
                           'createById' : getCurrentUserID(),
                           'updateTime' : dt.now(),
                           } )
            obj.update( params )

            oldaset = set( map( lambda v : unicode( v.id ), obj.attachment ) )
            newaset = set( filter( bool, _g( 'attachment', '' ).split( "|" ) ) )
            deltedAtm = oldaset.difference( newaset )
            if deltedAtm :
                delAtms = qry( SysFile ).filter( SysFile.id.in_( list( deltedAtm ) ) )
                extLog.extend( [u'删除附件[%s]。' % da.name for da in delAtms] )

            if newaset : obj.attachment = sorted( list( newaset ) ) + multiupload()
            else : obj.attachment = multiupload()

#             if not obj.attachment : obj.attachment = multiupload()
#             else : obj.attachment = map( lambda a : a.id, obj.attachment ) + multiupload()

            newCopy = obj.serialize()
            makeUpdateLog( obj, oldCopy, newCopy, extLog )
            db.commit()
            flash( MSG_UPDATE_SUCC, MESSAGE_INFO )
        except:
            db.rollback()
            flash( MSG_SERVER_ERROR, MESSAGE_ERROR )
            traceback.print_exc()
        return redirect( url_for( '.view', action = 'view', id = obj.id ) )


    @templated( 'view_log.html' )
    def viewLog( self ):
        sid = _g( 'id' )
        if not sid :
            flash( MSG_NO_ID_SUPPLIED, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )
        obj = self.dbclz.get( sid )
        if not obj :
            flash( MSG_RECORD_NOT_EXIST, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )
        return {'obj' : obj}




    def _isDuplicate( self, name ):
        try:
            qry( self.dbclz ).filter( self.dbclz.name == name ).one()
        except:
            return False
        else:
            flash( MSG_SAME_NAME_RECORD_EXIST, MESSAGE_ERROR )
            return True


bpSpl.add_url_rule( '/', view_func = SupplierView.as_view( 'view' ), defaults = {'action':'index'} )
bpSpl.add_url_rule( '/<action>', view_func = SupplierView.as_view( 'view' ) )



#===============================================================================
# form class
#===============================================================================

from wtforms import Form, TextField
from sys2do.util.wt_helper import MyDateField


class SrhForm( Form ):
    no = TextField( u'系统编号' )
    name = TextField( u'供应商名称' )
    att = TextField( u'联系人' )
    tel = TextField( u'电话' )
    mobile = TextField( u'手机' )
    createTimeFrom = MyDateField( u'创建时间(开始)' )
    createTimeTo = MyDateField( u'创建时间(结束)' )
